package gz.metro.datasync.utils;

/**
 * @author ：张任豪
 * @date ：2022/10/14 16:53
 * @description：
 */
public class StringUtils  {

    public static String format(String template, Object... args) {
        if (isEmpty(template)) {
            return "";
        } else if (null != args && args.length != 0) {
            char[] templateChars = template.toCharArray();
            int templateLength = templateChars.length;
            int length = 0;
            int tokenCount = args.length;

            for(int i = 0; i < tokenCount; ++i) {
                Object sourceString = args[i];
                if (sourceString != null) {
                    length += sourceString.toString().length();
                }
            }

            StringBuilder buffer = new StringBuilder(length + templateLength);
            int lastStart = 0;

            for(int i = 0; i < templateLength; ++i) {
                char ch = templateChars[i];
                if (ch == '{' && i + 2 < templateLength && templateChars[i + 2] == '}') {
                    int tokenIndex = templateChars[i + 1] - 48;
                    if (tokenIndex >= 0 && tokenIndex < tokenCount) {
                        buffer.append(templateChars, lastStart, i - lastStart);
                        Object sourceString = args[tokenIndex];
                        if (sourceString != null) {
                            buffer.append(sourceString.toString());
                        }

                        i += 2;
                        lastStart = i + 1;
                    }
                }
            }

            buffer.append(templateChars, lastStart, templateLength - lastStart);
            return new String(buffer);
        } else {
            return template;
        }
    }

    public static boolean isEmpty(CharSequence cs) {
        return isBlank(cs);
    }

    public static boolean isBlank(final CharSequence cs) {
        if (cs == null) {
            return true;
        }
        int l = cs.length();
        if (l > 0) {
            for (int i = 0; i < l; i++) {
                if (!Character.isWhitespace(cs.charAt(i))) {
                    return false;
                }
            }
        }
        return true;
    }


}
